package cn.code.mycloud.module.envir.controller.admin.grid;

import cn.code.mycloud.framework.apilog.core.annotation.ApiAccessLog;
import cn.code.mycloud.framework.common.pojo.CommonResult;
import cn.code.mycloud.framework.common.pojo.PageParam;
import cn.code.mycloud.framework.common.pojo.PageResult;
import cn.code.mycloud.framework.common.util.object.BeanUtils;
import cn.code.mycloud.framework.excel.core.util.ExcelUtils;
import cn.code.mycloud.module.envir.controller.admin.grid.vo.GridPageReqVO;
import cn.code.mycloud.module.envir.controller.admin.grid.vo.GridRespVO;
import cn.code.mycloud.module.envir.controller.admin.grid.vo.GridSaveReqVO;
import cn.code.mycloud.module.envir.controller.admin.usergrid.vo.AssignUserGridRespVO;
import cn.code.mycloud.module.envir.dal.dataobject.grid.GridDO;
import cn.code.mycloud.module.envir.service.grid.GridService;
import cn.code.mycloud.module.envir.service.usergrid.UserGridService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Set;

import static cn.code.mycloud.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.code.mycloud.framework.common.pojo.CommonResult.error;
import static cn.code.mycloud.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 网格")
@RestController
@RequestMapping("/envir/grid")
@Validated
public class GridController {

    @Resource
    private GridService gridService;

    @Resource
    private UserGridService userGridService;

    @PostMapping("/create")
    @Operation(summary = "创建网格")
    @PreAuthorize("@ss.hasPermission('envir:grid:create')")
    public CommonResult<Long> createGrid(@Valid @RequestBody GridSaveReqVO createReqVO) {
        return success(gridService.createGrid(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新网格")
    @PreAuthorize("@ss.hasPermission('envir:grid:update')")
    public CommonResult<Boolean> updateGrid(@Valid @RequestBody GridSaveReqVO updateReqVO) {
        gridService.updateGrid(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除网格")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('envir:grid:delete')")
    public CommonResult<Boolean> deleteGrid(@RequestParam("id") Long id) {
        // 判断是否设置了用户
        Set<Long> idListByGridId = userGridService.getGridUserIdListByGridId(id);
        if(!idListByGridId.isEmpty()){
            return error(-1,"该网格已设置用户，请先取消设置方可删除！");
        }
        gridService.deleteGrid(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得网格")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('envir:grid:query')")
    public CommonResult<GridRespVO> getGrid(@RequestParam("id") Long id) {
        GridDO grid = gridService.getGrid(id);
        return success(BeanUtils.toBean(grid, GridRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得网格分页")
    @PreAuthorize("@ss.hasPermission('envir:grid:query')")
    public CommonResult<PageResult<GridRespVO>> getGridPage(@Valid GridPageReqVO pageReqVO) {
        PageResult<GridDO> pageResult = gridService.getGridPage(pageReqVO);
        PageResult<GridRespVO> result = BeanUtils.toBean(pageResult, GridRespVO.class);
        return success(result);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出网格 Excel")
    @PreAuthorize("@ss.hasPermission('envir:grid:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportGridExcel(@Valid GridPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<GridDO> list = gridService.getGridPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "网格.xls", "数据", GridRespVO.class,
                        BeanUtils.toBean(list, GridRespVO.class));
    }

    @Operation(summary = "获得网格下用户列表")
    @Parameter(name = "gridId", description = "网格", required = true)
    @GetMapping("/list-grid-users")
    @PreAuthorize("@ss.hasPermission('envir:grid:assign-grid-user')")
    public CommonResult<Set<Long>> listGridUsers(@RequestParam("gridId") Long gridId) {
        return success(userGridService.getGridUserIdListByGridId(gridId));
    }

    @Operation(summary = "设置网格用户")
    @PostMapping("/assign-grid-user")
    @PreAuthorize("@ss.hasPermission('envir:grid:assign-grid-user')")
    public CommonResult<Boolean> assignGridUser(@Validated @RequestBody AssignUserGridRespVO reqVO) {
        userGridService.assignGridUser(reqVO.getGridId(), reqVO.getUserIds());
        return success(true);
    }

    @GetMapping( "/simple-list")
    @Operation(summary = "获取用户精简信息列表", description = "只包含被开启的用户，主要用于前端的下拉选项")
    public CommonResult<List<GridRespVO>> getSimpleUserList() {
        List<GridDO> list = gridService.selectAll();
        return success(BeanUtils.toBean(list, GridRespVO.class));
    }

}